/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Trabajos.java
 *
 * Created on 08-abr-2009, 16:53:32
 */

package laboratorio;

import gestion.Albaran;
import gestion.TrabajoProducto;
import clientes.Doctor;
import productos.Producto;
import clientes.Cliente;
import alertas.*;
import gestion.Trabajo;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import com.mysql.jdbc.jdbc2.optional.MysqlXAConnection;
import gestion.Fecha;
import gestion.FechaPK;
import java.util.*;
import javax.persistence.*;
import javax.print.DocFlavor.STRING;
import javax.swing.JOptionPane;
/**
 *
 * @author Juan Antonio Tirado
 */
public class Trabajos extends javax.swing.JFrame {
//Atributos
     private ListIterator it;
     private ListIterator itCliente;
     private ListIterator itDoctor;
     private ListIterator itProducto;
     private ListIterator itProductoAux;
     private ListIterator itAlbaran;

     private Trabajo old;
     private Trabajo trabajo;
     private Trabajo trabajoAux,x,x2,x3;
     private Cliente cliente;
     private Doctor doctor;
     private Producto producto;
     private TrabajoProducto trabajoproductoAux;
     private Albaran albaran;

     private Integer i,id;
     private Integer fila,row;
     private boolean enc,check;
     private boolean nuevo,guardar,err;
     
     private Integer aux;
     private List productos;
     private TrabajoProducto trapro;
     private Query q,q1,q2,q3,    q4;
     

 
    /** Creates new form Trabajos */
    public Trabajos() {
        initComponents();
        fila=0;
        err=false;
        nuevo=false;
        
        it=trabajoList.listIterator();
        if(it.hasNext()){
            trabajoAux=(Trabajo) it.next();
            setTrabajo(trabajoAux);
        }
        id=trabajoList.get(trabajoList.size()-1).getIDtrabajo()+1;
    
    }
    public Trabajo getTrabajo() {
        return trabajo;
    }

    public void setTrabajo(Trabajo trabajo){
        for(i=0;i<fila;i++){
            jTable3.setValueAt("", i, 0);//id producto
            jTable3.setValueAt("", i, 1);//concepto
            jTable3.setValueAt("", i, 2);//cantidad
            jTable3.setValueAt("", i, 3);//precio por unidad
        }
        for(i=0;i<6;i++){
            jTable1.setValueAt("", i, 0);
            jTable1.setValueAt("", i, 1);
        }

        old = this.trabajo;
        this.trabajo = trabajo;
        jTextField1.setText(String.valueOf(trabajo.getIDtrabajo()));//id trabajo
        jTextField2.setText(trabajo.getPaciente());//paciente
        jTextField3.setText(String.valueOf(trabajo.getIDcliente()));//id cliente
        
        jTextField7.setText(String.valueOf(trabajo.getFechaentrega()));//fecha entrega
        jTextArea1.setText(trabajo.getIncidencias());//incidencias

        enc=false;
        itCliente=clienteList.listIterator();
        while(itCliente.hasNext() && !enc){
            cliente=(Cliente) itCliente.next();
            if(cliente.getIDcliente()==trabajo.getIDcliente()){
                enc=true;
            }
        }
        jTextField4.setText(cliente.getNombre());//nombre cliente

        if(!(trabajo.getIDdoctor()==null)){
            enc=false;
            itDoctor=doctorList.listIterator();
            while(itDoctor.hasNext() && !enc){
                doctor=(Doctor) itDoctor.next();
                if(doctor.getIDdoctor()==trabajo.getIDdoctor()){
                    enc=true;
                    jTextField6.setText(doctor.getNombre());//nombre doctor
                    jTextField5.setText(String.valueOf(trabajo.getIDdoctor()));//id doctor
                }
            }
        }else{
            jTextField6.setText("");//nombre doctor
            jTextField5.setText("");//id doctor
        }
        
        
        if (trabajo.getTerminado()==true){
            jCheckBox1.setSelected(true);//boleano terminado
            check=true;
        }else{
            jCheckBox1.setSelected(false);
            check=false;
        }

        q = lpdPUEntityManager.createQuery("SELECT p FROM Producto AS p, TrabajoProducto AS t WHERE p.iDproducto=t.trabajoProductoPK.iDproducto AND t.trabajoProductoPK.iDtrabajo="+trabajo.getIDtrabajo());
        productos= q.getResultList();

        fila=0;
        itProducto=productos.listIterator();
        while(itProducto.hasNext()){
            producto=(Producto) itProducto.next();
            anadeProducto(producto);
        }
        Integer in=0;
        q2=lpdPUEntityManager.createQuery("SELECT f FROM Fecha f WHERE f.fechaPK.iDtrabajo="+trabajo.getIDtrabajo());
        List fechas=q2.getResultList();
        Iterator itfecha=fechas.iterator();
        while(itfecha.hasNext()){
            Fecha fecha =(Fecha) itfecha.next();
            jTable1.setValueAt(fecha.getFechaPK().getFechainicial(), in, 0);
            jTable1.setValueAt(fecha.getFechafinal(), in, 1);
            in++;

        }



    }

   public void anadeProducto(Producto productoSeleccionado) {
       q = lpdPUEntityManager.createQuery("SELECT t FROM TrabajoProducto AS t WHERE t.trabajoProductoPK.iDtrabajo="+trabajo.getIDtrabajo()+" AND t.trabajoProductoPK.iDproducto="+productoSeleccionado.getIDproducto());
            trapro= (TrabajoProducto)q.getSingleResult();
       if(!nuevo){
            jTable3.setValueAt(productoSeleccionado.getIDproducto(), fila, 0);//id producto
            jTable3.setValueAt(productoSeleccionado.getConcepto(), fila, 1);//concepto
            jTable3.setValueAt(trapro.getCantidad(), fila, 2);//cantidad
            jTable3.setValueAt(productoSeleccionado.getPrecio(), fila, 3);//precio por unidad
            fila++;
        }else{
            jTable3.setValueAt(productoSeleccionado.getIDproducto(), 0, 0);//id producto
            jTable3.setValueAt(productoSeleccionado.getConcepto(), 0, 1);//concepto
            jTable3.setValueAt(1,0, 2);//cantidad
            jTable3.setValueAt(productoSeleccionado.getPrecio(), 0, 3);//precio por unidad
            nuevo=false;
            fila=1;
        }
    }

   public void anadeProductoSelec(Producto productoSeleccionado) {
        //boolean b=productos.contains(productoSeleccionado);
        if(productos.contains(productoSeleccionado)&&!nuevo){//en el trabajo ya hay un producto de este tipo
            q2 = lpdPUEntityManager.createQuery("SELECT t FROM TrabajoProducto AS t WHERE t.trabajoProductoPK.iDtrabajo="+trabajo.getIDtrabajo()+" AND t.trabajoProductoPK.iDproducto="+productoSeleccionado.getIDproducto());
            trapro= (TrabajoProducto)q2.getSingleResult();
            //trabajoproductoAux= (TrabajoProducto) trapro.get(0);
            Integer cantidad=trapro.getCantidad()+1;
            TrabajoProducto t=new TrabajoProducto(trapro.getTrabajoProductoPK(),cantidad);
            lpdPUEntityManager.getTransaction().begin();
            lpdPUEntityManager.merge(t);
            lpdPUEntityManager.getTransaction().commit();
            
            for(int h=0;h<productoList.size();h++){
                producto=(Producto) productoList.get(h);
                if(producto.getIDproducto().equals(productoSeleccionado.getIDproducto())){
                    Integer a=t.getCantidad();
                    jTable3.setValueAt(a, h, 2);//cantidad
                    h=productoList.size();
                }
            }
        }else{//en el trabajo no hay ningun producto de este tipo

            TrabajoProducto t=new TrabajoProducto(this.getTrabajo().getIDtrabajo(),productoSeleccionado.getIDproducto(),1);
            lpdPUEntityManager.getTransaction().begin();
            lpdPUEntityManager.persist(t);
            lpdPUEntityManager.getTransaction().commit();
            anadeProducto(productoSeleccionado);
            nuevo=false;
        }
    }

    public void setCliente(Cliente clienteSeleccionado) {
        jTextField3.setText(String.valueOf(clienteSeleccionado.getIDcliente()));//id cliente
        jTextField4.setText(clienteSeleccionado.getNombre());//nombre cliente
    }

   public  void setDoctor(Doctor doctorSeleccionado) {
        //aki deberiamos de hacer algo porque la idea seria que saliera los doctores del cliente seleccionado y no todos los clientes
        jTextField5.setText(String.valueOf(doctorSeleccionado.getIDdoctor()));//id doctor
        jTextField6.setText(doctorSeleccionado.getNombre());//nombre doctor
    }

   public  void setTrabajoSelec(Trabajo trabajoSeleccionado) {
        setTrabajo(trabajoSeleccionado);
        enc=false;
        it=trabajoList.listIterator();
        while(it.hasNext() && !enc){
            trabajoAux=(Trabajo) it.next();
            if(trabajoAux.equals(trabajo)){
                enc=true;
            }
        }
    }

    

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        lpdPUEntityManager = java.beans.Beans.isDesignTime() ? null : javax.persistence.Persistence.createEntityManagerFactory("lpdPU").createEntityManager();
        trabajoQuery = java.beans.Beans.isDesignTime() ? null : lpdPUEntityManager.createQuery("SELECT t FROM Trabajo t");
        trabajoList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : trabajoQuery.getResultList();
        clienteQuery = java.beans.Beans.isDesignTime() ? null : lpdPUEntityManager.createQuery("SELECT c FROM Cliente c");
        clienteList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : clienteQuery.getResultList();
        doctorQuery = java.beans.Beans.isDesignTime() ? null : lpdPUEntityManager.createQuery("SELECT d FROM Doctor d");
        doctorList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : doctorQuery.getResultList();
        albaranQuery = java.beans.Beans.isDesignTime() ? null : lpdPUEntityManager.createQuery("SELECT a FROM Albaran a");
        albaranList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : albaranQuery.getResultList();
        productoQuery = java.beans.Beans.isDesignTime() ? null : lpdPUEntityManager.createQuery("SELECT p FROM Producto p");
        productoList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : productoQuery.getResultList();
        fechaQuery = java.beans.Beans.isDesignTime() ? null : lpdPUEntityManager.createQuery("SELECT f FROM Fecha f");
        fechaList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : fechaQuery.getResultList();
        jPanel1 = new javax.swing.JPanel();
        jTextField1 = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jTextField2 = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jTextField3 = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jTextField4 = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        jTextField5 = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        jTextField6 = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jScrollPane3 = new javax.swing.JScrollPane();
        jTable2 = new javax.swing.JTable();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton9 = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jButton5 = new javax.swing.JButton();
        jScrollPane4 = new javax.swing.JScrollPane();
        jTable3 = new javax.swing.JTable();
        jButton6 = new javax.swing.JButton();
        jButton7 = new javax.swing.JButton();
        jCheckBox1 = new javax.swing.JCheckBox();
        jLabel8 = new javax.swing.JLabel();
        jTextField7 = new javax.swing.JTextField();
        jButton8 = new javax.swing.JButton();
        jButton10 = new javax.swing.JButton();
        jButton11 = new javax.swing.JButton();
        jButton12 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(laboratorio.LaboratorioApp.class).getContext().getResourceMap(Trabajos.class);
        setTitle(resourceMap.getString("Form.title")); // NOI18N
        setName("Form"); // NOI18N

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, resourceMap.getString("jPanel1.border.title"), javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, resourceMap.getFont("jPanel1.border.titleFont"), resourceMap.getColor("jPanel1.border.titleColor"))); // NOI18N
        jPanel1.setName("jPanel1"); // NOI18N

        jTextField1.setName("jTextField1"); // NOI18N

        jLabel1.setFont(resourceMap.getFont("jLabel1.font")); // NOI18N
        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        jLabel2.setFont(resourceMap.getFont("jLabel2.font")); // NOI18N
        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N

        jTextField2.setText(resourceMap.getString("jTextField2.text")); // NOI18N
        jTextField2.setName("jTextField2"); // NOI18N

        jLabel3.setFont(resourceMap.getFont("jLabel3.font")); // NOI18N
        jLabel3.setText(resourceMap.getString("jLabel3.text")); // NOI18N
        jLabel3.setName("jLabel3"); // NOI18N

        jTextField3.setText(resourceMap.getString("jTextField3.text")); // NOI18N
        jTextField3.setName("jTextField3"); // NOI18N

        jLabel4.setFont(resourceMap.getFont("jLabel4.font")); // NOI18N
        jLabel4.setText(resourceMap.getString("jLabel4.text")); // NOI18N
        jLabel4.setName("jLabel4"); // NOI18N

        jTextField4.setText(resourceMap.getString("jTextField4.text")); // NOI18N
        jTextField4.setName("jTextField4"); // NOI18N

        jLabel5.setFont(resourceMap.getFont("jLabel5.font")); // NOI18N
        jLabel5.setText(resourceMap.getString("jLabel5.text")); // NOI18N
        jLabel5.setName("jLabel5"); // NOI18N

        jTextField5.setText(resourceMap.getString("jTextField5.text")); // NOI18N
        jTextField5.setName("jTextField5"); // NOI18N

        jLabel6.setFont(resourceMap.getFont("jLabel6.font")); // NOI18N
        jLabel6.setText(resourceMap.getString("jLabel6.text")); // NOI18N
        jLabel6.setName("jLabel6"); // NOI18N

        jTextField6.setText(resourceMap.getString("jTextField6.text")); // NOI18N
        jTextField6.setName("jTextField6"); // NOI18N

        jLabel7.setFont(resourceMap.getFont("jLabel7.font")); // NOI18N
        jLabel7.setText(resourceMap.getString("jLabel7.text")); // NOI18N
        jLabel7.setName("jLabel7"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);
        jTextArea1.setName("jTextArea1"); // NOI18N
        jScrollPane1.setViewportView(jTextArea1);

        jScrollPane3.setName("jScrollPane3"); // NOI18N

        jTable2.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null}
            },
            new String [] {
                "Salida1", "Salida2", "Salida3"
            }
        ));
        jTable2.setName("jTable2"); // NOI18N
        jScrollPane3.setViewportView(jTable2);
        jTable2.getColumnModel().getColumn(0).setHeaderValue(resourceMap.getString("jTable2.columnModel.title0")); // NOI18N
        jTable2.getColumnModel().getColumn(1).setHeaderValue(resourceMap.getString("jTable2.columnModel.title1")); // NOI18N
        jTable2.getColumnModel().getColumn(2).setHeaderValue(resourceMap.getString("jTable2.columnModel.title2")); // NOI18N

        jButton1.setFont(resourceMap.getFont("jButton1.font")); // NOI18N
        jButton1.setIcon(resourceMap.getIcon("jButton1.icon")); // NOI18N
        jButton1.setText(resourceMap.getString("jButton1.text")); // NOI18N
        jButton1.setName("jButton1"); // NOI18N
        jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                buscarCliente(evt);
            }
        });

        jButton2.setFont(resourceMap.getFont("jButton2.font")); // NOI18N
        jButton2.setIcon(resourceMap.getIcon("jButton2.icon")); // NOI18N
        jButton2.setText(resourceMap.getString("jButton2.text")); // NOI18N
        jButton2.setName("jButton2"); // NOI18N
        jButton2.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                buscarDoctor(evt);
            }
        });

        jButton9.setFont(resourceMap.getFont("jButton9.font")); // NOI18N
        jButton9.setIcon(resourceMap.getIcon("jButton9.icon")); // NOI18N
        jButton9.setText(resourceMap.getString("jButton9.text")); // NOI18N
        jButton9.setName("jButton9"); // NOI18N
        jButton9.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                BuscarTrabajos(evt);
            }
        });

        jScrollPane2.setName("jScrollPane2"); // NOI18N

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null},
                {null, null}
            },
            new String [] {
                "Fecha entrada", "Fecha salida"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTable1.setName("jTable1"); // NOI18N
        jScrollPane2.setViewportView(jTable1);
        jTable1.getColumnModel().getColumn(0).setResizable(false);
        jTable1.getColumnModel().getColumn(0).setHeaderValue(resourceMap.getString("jTable1.columnModel.title0")); // NOI18N
        jTable1.getColumnModel().getColumn(1).setResizable(false);
        jTable1.getColumnModel().getColumn(1).setHeaderValue(resourceMap.getString("jTable1.columnModel.title1")); // NOI18N

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(20, 20, 20)
                        .addComponent(jLabel7))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addContainerGap()
                                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 348, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                                .addContainerGap()
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(jTextField1)
                                    .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                .addGap(61, 61, 61)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 205, javax.swing.GroupLayout.PREFERRED_SIZE))))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(12, 12, 12)
                                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 211, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(49, 49, 49)
                                .addComponent(jButton9))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(jTextField3)
                                    .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 28, Short.MAX_VALUE)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel4)
                                    .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, 189, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 38, Short.MAX_VALUE)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(jTextField5, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jLabel5, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE))))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(937, 937, 937)
                        .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 0, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jLabel6)
                    .addComponent(jButton2)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(4, 4, 4)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(jButton1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jTextField6, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 155, Short.MAX_VALUE))))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2)
                            .addComponent(jLabel4)
                            .addComponent(jLabel5)
                            .addComponent(jLabel6)
                            .addComponent(jLabel3))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jTextField6, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 32, Short.MAX_VALUE)
                                    .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jTextField4, javax.swing.GroupLayout.DEFAULT_SIZE, 32, Short.MAX_VALUE)
                                    .addComponent(jTextField3, javax.swing.GroupLayout.DEFAULT_SIZE, 32, Short.MAX_VALUE))
                                .addGroup(jPanel1Layout.createSequentialGroup()
                                    .addComponent(jTextField5, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))))
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(6, 6, 6)
                                .addComponent(jLabel7)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(jPanel1Layout.createSequentialGroup()
                                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 156, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(343, 343, 343)
                                        .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                        .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.LEADING, 0, 0, Short.MAX_VALUE)
                                        .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                                            .addGap(94, 94, 94)
                                            .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(67, 67, 67)
                                .addComponent(jButton9, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE))))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(84, 84, 84)
                        .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );

        jButton3.setFont(resourceMap.getFont("jButton3.font")); // NOI18N
        jButton3.setIcon(resourceMap.getIcon("jButton3.icon")); // NOI18N
        jButton3.setText(resourceMap.getString("jButton3.text")); // NOI18N
        jButton3.setName("jButton3"); // NOI18N
        jButton3.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                salir(evt);
            }
        });

        jButton4.setFont(resourceMap.getFont("jButton4.font")); // NOI18N
        jButton4.setIcon(resourceMap.getIcon("jButton4.icon")); // NOI18N
        jButton4.setText(resourceMap.getString("jButton4.text")); // NOI18N
        jButton4.setName("jButton4"); // NOI18N
        jButton4.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                nuevo(evt);
            }
        });

        jButton5.setFont(resourceMap.getFont("jButton5.font")); // NOI18N
        jButton5.setIcon(resourceMap.getIcon("jButton5.icon")); // NOI18N
        jButton5.setText(resourceMap.getString("jButton5.text")); // NOI18N
        jButton5.setName("jButton5"); // NOI18N
        jButton5.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                Guardar(evt);
            }
        });

        jScrollPane4.setName("jScrollPane4"); // NOI18N

        jTable3.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Nº Artículo", "Concepto", "Cantidad", "Precio/Unidad"
            }
        ));
        jTable3.setName("jTable3"); // NOI18N
        jScrollPane4.setViewportView(jTable3);
        jTable3.getColumnModel().getColumn(0).setHeaderValue(resourceMap.getString("jTable3.columnModel.title0")); // NOI18N
        jTable3.getColumnModel().getColumn(1).setHeaderValue(resourceMap.getString("jTable3.columnModel.title1")); // NOI18N
        jTable3.getColumnModel().getColumn(2).setHeaderValue(resourceMap.getString("jTable3.columnModel.title2")); // NOI18N
        jTable3.getColumnModel().getColumn(3).setHeaderValue(resourceMap.getString("jTable3.columnModel.title4")); // NOI18N

        jButton6.setFont(resourceMap.getFont("jButton6.font")); // NOI18N
        jButton6.setIcon(resourceMap.getIcon("jButton6.icon")); // NOI18N
        jButton6.setText(resourceMap.getString("jButton6.text")); // NOI18N
        jButton6.setName("jButton6"); // NOI18N
        jButton6.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                buscarProducto(evt);
            }
        });

        jButton7.setFont(resourceMap.getFont("jButton7.font")); // NOI18N
        jButton7.setIcon(resourceMap.getIcon("jButton7.icon")); // NOI18N
        jButton7.setText(resourceMap.getString("jButton7.text")); // NOI18N
        jButton7.setName("jButton7"); // NOI18N
        jButton7.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                EliminarProducto(evt);
            }
        });

        jCheckBox1.setFont(resourceMap.getFont("jCheckBox1.font")); // NOI18N
        jCheckBox1.setText(resourceMap.getString("jCheckBox1.text")); // NOI18N
        jCheckBox1.setName("jCheckBox1"); // NOI18N
        jCheckBox1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                terminar(evt);
            }
        });

        jLabel8.setFont(resourceMap.getFont("jLabel8.font")); // NOI18N
        jLabel8.setText(resourceMap.getString("jLabel8.text")); // NOI18N
        jLabel8.setName("jLabel8"); // NOI18N

        jTextField7.setText(resourceMap.getString("jTextField7.text")); // NOI18N
        jTextField7.setName("jTextField7"); // NOI18N

        jButton8.setFont(resourceMap.getFont("jButton8.font")); // NOI18N
        jButton8.setIcon(resourceMap.getIcon("jButton8.icon")); // NOI18N
        jButton8.setText(resourceMap.getString("jButton8.text")); // NOI18N
        jButton8.setName("jButton8"); // NOI18N
        jButton8.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                crearAlbaran(evt);
            }
        });

        jButton10.setFont(resourceMap.getFont("jButton10.font")); // NOI18N
        jButton10.setText(resourceMap.getString("jButton10.text")); // NOI18N
        jButton10.setName("jButton10"); // NOI18N
        jButton10.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                Anterior(evt);
            }
        });

        jButton11.setFont(resourceMap.getFont("jButton11.font")); // NOI18N
        jButton11.setText(resourceMap.getString("jButton11.text")); // NOI18N
        jButton11.setName("jButton11"); // NOI18N
        jButton11.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                Siguiente(evt);
            }
        });

        jButton12.setFont(resourceMap.getFont("jButton12.font")); // NOI18N
        jButton12.setIcon(resourceMap.getIcon("jButton12.icon")); // NOI18N
        jButton12.setText(resourceMap.getString("jButton12.text")); // NOI18N
        jButton12.setName("jButton12"); // NOI18N
        jButton12.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                Eliminar(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton10)
                        .addGap(16, 16, 16)
                        .addComponent(jButton11)
                        .addGap(44, 44, 44)
                        .addComponent(jButton4)
                        .addGap(38, 38, 38)
                        .addComponent(jButton5)
                        .addGap(18, 18, 18)
                        .addComponent(jButton12)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButton3))
                    .addComponent(jPanel1, 0, 994, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(27, 27, 27)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jButton6)
                            .addComponent(jButton7))
                        .addGap(36, 36, 36)
                        .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(45, 45, 45)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(jLabel8)
                                        .addGap(30, 30, 30)
                                        .addComponent(jTextField7, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addComponent(jButton8)))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(55, 55, 55)
                                .addComponent(jCheckBox1)))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton5, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton10, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton11, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton12, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 84, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 327, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButton6, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(21, 21, 21)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel8)
                            .addComponent(jTextField7, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(27, 27, 27)
                        .addComponent(jButton8, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(37, 37, 37)
                        .addComponent(jCheckBox1))
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addComponent(jButton7, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 228, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void buscarCliente(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_buscarCliente
        ListaClientes lis=new ListaClientes(this);
        lis.setVisible(true);
}//GEN-LAST:event_buscarCliente

    private void buscarDoctor(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_buscarDoctor
        ListaDoctores list = new ListaDoctores(this,jTextField3.getText());
        list.setVisible(true);
    }//GEN-LAST:event_buscarDoctor

    private void salir(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_salir
        alertGuardar a= new alertGuardar(this);
        this.guardar();
        a.setVisible(true);
    }//GEN-LAST:event_salir

    private void buscarProducto(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_buscarProducto
        ListaProductos lp=new ListaProductos(this);
        lp.setVisible(true);
}//GEN-LAST:event_buscarProducto

    private void Siguiente(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_Siguiente
        if(it.hasNext()){
            setTrabajo((Trabajo)it.next());}
    }//GEN-LAST:event_Siguiente

    private void Anterior(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_Anterior
        if(it.hasPrevious()){
            setTrabajo((Trabajo)it.previous());}
    }//GEN-LAST:event_Anterior

    private void BuscarTrabajos(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_BuscarTrabajos
         ListaTrabajos lis=new ListaTrabajos(this);
         lis.setVisible(true);
    }//GEN-LAST:event_BuscarTrabajos

    private void nuevo(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_nuevo
        Trabajo nuev= new Trabajo(id);
        nuev.setIDcliente(1);
        id++;
        lpdPUEntityManager.getTransaction().begin();
        lpdPUEntityManager.persist(nuev);
        lpdPUEntityManager.getTransaction().commit();

        Date d=new Date();
        String s=String.valueOf(d.getDate()).concat("-").concat(String.valueOf(d.getMonth()+1)).concat("-").concat(String.valueOf(d.getYear()+1900));

        Fecha f=new Fecha(nuev.getIDtrabajo(),s);
 
        lpdPUEntityManager.getTransaction().begin();
        lpdPUEntityManager.persist(f);
        lpdPUEntityManager.getTransaction().commit();



        old = this.trabajo;
        this.trabajo =nuev;

        jTextArea1.setText("");//incidencias
        jTextField1.setText(String.valueOf(nuev.getIDtrabajo()));// id trabajo
        jTextField2.setText("");//paciente
        jTextField3.setText(String.valueOf(0));//id cliente
        jTextField4.setText("");//nombre cliente
        jTextField5.setText("");//id doctor
        jTextField6.setText("");//nombre doctor
        jTextField7.setText("");//fecha entrega



        for(i=0;i<15;i++){
            jTable3.setValueAt(null, i, 0);
            jTable3.setValueAt(null, i, 1);
            jTable3.setValueAt(null, i, 2);
            jTable3.setValueAt(null, i, 3);
        }
        for(i=0;i<productos.size();i++){
            productos.remove(i);
        }
        for (int j=0;j<4;j++){
            jTable1.setValueAt("", j, 0);
            jTable1.setValueAt("", j, 1);
        }

        jCheckBox1.setSelected(false);//boleano terminado
        nuevo=true;

       
    }//GEN-LAST:event_nuevo

    private void Eliminar(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_Eliminar
        if(trabajo.getTerminado()==true){
            JOptionPane.showMessageDialog(this,"Este trabajo ya esta terminado,luego no puede ser eliminado");
        }else{
        trabajoList.remove(trabajo);
        alertEliminar a=new alertEliminar(this);
        a.setVisible(true);
         }
}//GEN-LAST:event_Eliminar

    private void Guardar(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_Guardar
        this.guardar();

    }//GEN-LAST:event_Guardar

    private void guardar(){
    Trabajo t=CogeTrabajo();

        lpdPUEntityManager.getTransaction().begin();
        lpdPUEntityManager.merge(t);
        lpdPUEntityManager.getTransaction().commit();
        if(nuevo=false){
            itAlbaran=albaranList.listIterator();
            while(itAlbaran.hasNext()){
                albaran=(Albaran)itAlbaran.next();
                if (albaran.getIDtrabajo()==t.getIDtrabajo()){
                     lpdPUEntityManager.getTransaction().begin();
                     lpdPUEntityManager.merge(albaran);
                     lpdPUEntityManager.getTransaction().commit();
                }
            }
        }
        nuevo=false;
    }


    private void EliminarProducto(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_EliminarProducto
        row=-1;
        row=jTable3.getSelectedRow();
        System.out.print(row);
        if(row==-1){
                JOptionPane.showMessageDialog(this,"No ha seleccionado ninguna fila");
        }else{
        int a =Integer.parseInt(jTable3.getValueAt(row, 0).toString());
        q4=lpdPUEntityManager.createQuery("SELECT tp FROM TrabajoProducto tp WHERE tp.trabajoProductoPK.iDproducto="+a+ " AND tp.trabajoProductoPK.iDtrabajo="+trabajo.getIDtrabajo());
        List trabajProduct=q4.getResultList();
        TrabajoProducto trabajoProducto1=(TrabajoProducto) trabajProduct.get(0);
        int cantidad= trabajoProducto1.getCantidad()-1;
        if(cantidad<=0){//ya no quedarian productos de este tipo en este trabajo
            lpdPUEntityManager.getTransaction().begin();
            lpdPUEntityManager.remove(trabajoProducto1);
            lpdPUEntityManager.getTransaction().commit();
            setTrabajoSelec(trabajo);
        }else{//hay que decrementar la cantidad de este producto en este trabajo
            trabajoProducto1.setCantidad(cantidad);
            lpdPUEntityManager.getTransaction().begin();
            lpdPUEntityManager.merge(trabajoProducto1);
            lpdPUEntityManager.getTransaction().commit();
            jTable3.setValueAt(cantidad, row, 2);//cantidad
        }
        }

    }//GEN-LAST:event_EliminarProducto

    private void crearAlbaran(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_crearAlbaran
        if(getTrabajo().getTerminado()){
            JOptionPane.showMessageDialog(this,"Este trabajo ya esta terminado, no puede generar otro albaran");
        }else{
        alertCreaAlbaran ca=new alertCreaAlbaran(this);
        ca.setVisible(true);
        jCheckBox1.setSelected(true);
        Trabajo trab=CogeTrabajo();
        lpdPUEntityManager.getTransaction().begin();
        lpdPUEntityManager.merge(trab);
        lpdPUEntityManager.getTransaction().commit();

    }
    }//GEN-LAST:event_crearAlbaran

    private void terminar(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_terminar
        Date d=new Date();
        String s=String.valueOf(d.getDate()).concat("-").concat(String.valueOf(d.getMonth()+1)).concat("-").concat(String.valueOf(d.getYear()+1900));

        if(check){
            FechaPK fpk=new FechaPK(trabajo.getIDtrabajo(),s);
            Fecha fecha=new Fecha(fpk);
            lpdPUEntityManager.getTransaction().begin();
            lpdPUEntityManager.persist(fecha);
            lpdPUEntityManager.getTransaction().commit();
            jCheckBox1.setSelected(false);
        }else{
            q=lpdPUEntityManager.createQuery("SELECT f FROM Fecha f WHERE f.fechaPK.iDtrabajo="+trabajo.getIDtrabajo());
            List fechas=q.getResultList();
            Fecha fecha=(Fecha) fechas.get(fechas.size()-1);
            fecha.setFechafinal(s);
            lpdPUEntityManager.getTransaction().begin();
            lpdPUEntityManager.merge(fecha);
            lpdPUEntityManager.getTransaction().commit();
            jCheckBox1.setSelected(true);
        }
        trabajo.setFechaentrega("");
        trabajo.setTerminado(jCheckBox1.isSelected());
        lpdPUEntityManager.getTransaction().begin();
        lpdPUEntityManager.merge(trabajo);
        lpdPUEntityManager.getTransaction().commit();
        

        this.setTrabajo(trabajo);



    }//GEN-LAST:event_terminar

    public Trabajo CogeTrabajo(){
        String IDtrabajo=jTextField1.getText();//id trabajo
        String Paciente=jTextField2.getText();//paciente
        String IDcliente=jTextField3.getText();//id cliente
        String IDdoctor=jTextField5.getText();//id doctor
        String Fechaentrega=jTextField7.getText();//fecha entrega
        String Incidencias=jTextArea1.getText();//incidencias

        

        Boolean Terminado=jCheckBox1.isSelected();
        trabajoAux=new Trabajo(IDtrabajo,Paciente,IDcliente,IDdoctor,Fechaentrega,Incidencias,Terminado);
        return trabajoAux;
    }


    private boolean cambiar(Trabajo x, Trabajo x2) {
        guardar=false;
        err=false;
        if (nuevo){
            guardar=true;
        }
        if(!(x.getIDtrabajo().equals(x2.getIDtrabajo()))){
            alertError error=new alertError("No se puede cambiar el id del trabajo",this);
            error.setVisible(true);
            err=true;
            guardar=false;
            jTextField1.setText(String.valueOf(x2.getIDtrabajo()));
       /* }else if(x.getIDcliente()==0 || x.getEntrada1().equals("0-0-0")){
            alertError error=new alertError("El cliente o la fecha de entrada 1 no puede estar vacio",this);
            error.setVisible(true);
            err=true;
            guardar=false;
        }else{
            if(!(x.getEntrada2()==null)){
                if(!(x.getEntrada2().equals(x2.getEntrada2()))){
                    guardar=true;
                }
            }
            if(!(x.getTerminado()==x2.getTerminado())){
                guardar=true;
            }
            if(!(x.getEntrada1().equals(x2.getEntrada1())) ){
                guardar=true;
            }
            if(!(x.getEntrada3()==null)){
                if(!(x.getEntrada3().equals(x2.getEntrada3()))){
                    guardar=true;
                }
            }
            if(!(x.getSalida1()==null)){
                if(!(x.getSalida1().equals(x2.getSalida1()))){
                    guardar=true;
                }
            }
            if(!(x.getSalida2()==null)){
                if(!(x.getSalida2().equals(x2.getSalida2()))){
                    guardar=true;
                }
            }
            if(!(x.getSalida3()==null)){
                if(!(x.getSalida3().equals(x2.getSalida3()))){
                    guardar=true;
                }
            }*/
            if(!(x.getFechaentrega()==null)){
                if(!(x.getFechaentrega().equals(x2.getFechaentrega()))){
                    guardar=true;
                }
            }
            if(!(x.getIDcliente()==x2.getIDcliente())){
                guardar=true;
            }
            if(!(x.getIDdoctor()==null)){
                if(!(x.getIDdoctor()==x2.getIDdoctor())){
                    guardar=true;
                }
            }
            if(!(x.getIncidencias()==null)){
                if(!(x.getIncidencias().equals(x2.getIncidencias())) ){
                    guardar=true;
                }
            }
            if(!(x.getPaciente()==null)){
                if(!(x.getPaciente().equals(x2.getPaciente()))){
                    guardar=true;
                }
            }
        }
        return guardar;
    }












    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Trabajos().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private java.util.List<gestion.Albaran> albaranList;
    private javax.persistence.Query albaranQuery;
    private java.util.List<clientes.Cliente> clienteList;
    private javax.persistence.Query clienteQuery;
    private java.util.List<clientes.Doctor> doctorList;
    private javax.persistence.Query doctorQuery;
    private java.util.List<gestion.Fecha> fechaList;
    private javax.persistence.Query fechaQuery;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton10;
    private javax.swing.JButton jButton11;
    private javax.swing.JButton jButton12;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton5;
    private javax.swing.JButton jButton6;
    private javax.swing.JButton jButton7;
    private javax.swing.JButton jButton8;
    private javax.swing.JButton jButton9;
    private javax.swing.JCheckBox jCheckBox1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JTable jTable1;
    private javax.swing.JTable jTable2;
    private javax.swing.JTable jTable3;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JTextField jTextField3;
    private javax.swing.JTextField jTextField4;
    private javax.swing.JTextField jTextField5;
    private javax.swing.JTextField jTextField6;
    private javax.swing.JTextField jTextField7;
    private javax.persistence.EntityManager lpdPUEntityManager;
    private java.util.List<productos.Producto> productoList;
    private javax.persistence.Query productoQuery;
    private java.util.List<gestion.Trabajo> trabajoList;
    private javax.persistence.Query trabajoQuery;
    // End of variables declaration//GEN-END:variables

}
